package com.alg.local.gateway.config;

import com.alg.local.gateway.entity.EncrProps;
import com.alg.local.gateway.util.AsymmetricEncryptionUtil;
import com.alg.local.gateway.util.Base64Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author al
 * @date 2022/5/31 11:38
 * @description
 */
@Component
@Slf4j
public class InitialCaInfos implements CommandLineRunner {

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    EncrProps encrProps;

    @Override
    public void run(String... args) throws Exception {
        AsymmetricEncryptionUtil rsa = AsymmetricEncryptionUtil.build(2048, "RSA");
        Map<String, String> simpleMapTest = redissonClient.getMap(GatewayConstant.RSA_KEY_MAP, new StringCodec());
        if (StringUtils.isEmpty(simpleMapTest.get(GatewayConstant.ENC_AES_KEY))) {
            log.info("initial system CA-key and default AES-key");
            simpleMapTest.put(GatewayConstant.RSA_PUB_KEY, Base64Util.encoder(rsa.getPublicKeyByte()));
            simpleMapTest.put(GatewayConstant.RSA_PRI_KEY, Base64Util.encoder(rsa.getPrivateKeyByte()));
            simpleMapTest.put(GatewayConstant.ENC_AES_KEY, encrProps.getAesKey());
        }
        log.info("CA-key and default AES-key exist");
    }
}
